package com.feng.gaoerfu.fragment;

import android.content.Context;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.view.WindowManager;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.PopupWindow;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.feng.gaoerfu.R;
import com.feng.gaoerfu.adapter.MyPickerDataProvider;
import com.feng.gaoerfu.adapter.MyTableAdapter;
import com.feng.gaoerfu.base.App;
import com.feng.gaoerfu.base.BaseFragment;
import com.feng.gaoerfu.bean.GolfHoleBean;
import com.feng.gaoerfu.bean.TableData;
import com.feng.gaoerfu.bean.TitleData;
import com.feng.gaoerfu.holder.FooterViewHolder;
import com.feng.gaoerfu.holder.HeaderViewHolder;
import com.feng.gaoerfu.utils.StringUtils;
import com.feng.gaoerfu.utils.T;
import com.feng.gaoerfu.utils.UIUtils;
import com.feng.gaoerfu.view.framework.picker.LinkagePicker;
import com.feng.gaoerfu.view.locktableview.DisplayUtil;
import com.feng.gaoerfu.view.locktableview.LockTableView;
import com.feng.gaoerfu.view.locktableview.TotalViewLayout;

import java.util.ArrayList;

import butterknife.ButterKnife;
import butterknife.InjectView;
import butterknife.OnClick;

/**
 * @time 2017/8/2 0002 20:56
 */
public class ScroingFragment extends BaseFragment implements View.OnClickListener,
        LockTableView.onClickItemListener, FooterViewHolder.FooterViewListener {
    @InjectView(R.id.tv_1)
    TextView mTv1;
    @InjectView(R.id.tv_time)
    TextView mTvTime;
    @InjectView(R.id.layout_1)
    LinearLayout mLayout1;
    @InjectView(R.id.tv_details)
    TextView mTvDetails;
    @InjectView(R.id.contentView)
    LinearLayout mContentView;
    @InjectView(R.id.line_right)
    View mLineRight;
    @InjectView(R.id.tv_total)
    TextView mTvTotal;
    @InjectView(R.id.layout_total)
    LinearLayout mLayoutTotal;
    @InjectView(R.id.line_mid)
    View mLineMid;
    @InjectView(R.id.content_end)
    RelativeLayout mContentEnd;
    @InjectView(R.id.layout_scroing)
    LinearLayout mLayoutScroing;
    @InjectView(R.id.layout_total_view)
    FrameLayout mLayoutTotalView;

    private String tab = "         ";
    private String line = "\n";
    private PopupWindow mPopWnd;
    private LinkagePicker mPicker;
    private ArrayList<TitleData> mTitleDatas;

    private LockTableView mLockTableView;
    private View mTotalView;
    private int mRow;//行
    private int mColumn;//列
    private MyTableAdapter mMyTableAdapter;
    private int mHeight;
    private FooterViewHolder mFooterViewHolder;
    private HeaderViewHolder mHeaderViewHolder;


    @Override
    protected int initContentView() {
        return R.layout.fragment_scroing;
    }

    @Override
    public void initData() {
        initScreenParams();
        //初始化标题数据
        initTitle();
        //构造假数据
        initFormView();

        initPopView();
        initListener();
    }

    private void initTitle() {
        //        StringBuilder sb = new StringBuilder();
        //        sb.append("球场名称:").append(tab).append("(18洞)广东省深圳名商高尔夫俱乐部球场A场/B场").append(line)
        //                .append("开球时间:").append(tab).append("2017-08-07 09:21:12").append(line);
        //        //                .append("入场价格:").append(tab).append("-").append(line)
        //        //                .append("打球备注:").append(tab).append("无").append(line).append(line)
        //        //                .append("是否公开:").append(tab).append("公开:(关注我的人都可见)").append(line)
        //        //                .append("打球规则:").append(tab).append("球场规则(默认)");
        //        mTvDetails.setText(sb);

        mTv1.setText("球场名称: " + App.mBallCourt);
        mTvTime.setText("开球时间: " + App.mOpenTime);
    }

    private void initFormView() {
        initDisplayOpinion();
        getTableData();

        setTableViewWithData();

    }

    private void setTableViewWithData() {
        //设置表格
        mLockTableView = new LockTableView(mContext, mContentView);
        Log.d("表格加载开始", "当前线程：" + Thread.currentThread());
        mMyTableAdapter = new MyTableAdapter(mTitleDatas, App.mPersonList, App.mTableLists);
        mLockTableView
                .setMaxColumnWidth(100) //列最大宽度
                .setMinColumnWidth(60) //列最小宽度
                .setMinRowHeight(20)//行最小高度
                .setMaxRowHeight(60)//行最大高度
                .setFristRowBackGroudColor(R.color.white)//表头背景色
                .setTableHeadTextColor(R.color.border_color)//表头字体颜色
                .setTableContentTextColor(R.color.border_color)//单元格字体颜色
                .setTableViewListener(new LockTableView.OnTableViewListener() {
                    @Override
                    public void onTableViewScrollChange(int x, int y) {
                        //                        Log.d("滚动值", "[" + x + "]" + "[" + y + "]");
                    }
                })//设置滚动回调监听
                .setOnClickListener(this)
                .setAdapter(mMyTableAdapter)
                .show(); //显示表格,此方法必须调用
        //设置最后一列
        int total = 0;
        for (GolfHoleBean data : App.mGolfHoleList) {
            total += data.ganNum;
        }
        mTvTotal.setText(total + "");

        mTotalView = new TotalViewLayout(mContext, App.mTableLists).initView();
        mLayoutTotalView.addView(mTotalView);
    }


    private void initDisplayOpinion() {
        DisplayMetrics dm = getResources().getDisplayMetrics();
        DisplayUtil.density = dm.density;
        DisplayUtil.densityDPI = dm.densityDpi;
        DisplayUtil.screenWidthPx = dm.widthPixels;
        DisplayUtil.screenhightPx = dm.heightPixels;
        DisplayUtil.screenWidthDip = DisplayUtil.px2dip(mContext, dm.widthPixels);
        DisplayUtil.screenHightDip = DisplayUtil.px2dip(mContext, dm.heightPixels);
    }

    private void getTableData() {

        //标题
        mTitleDatas = new ArrayList<>();
        for (int i = 0; i < App.mGolfHoleList.size(); i++) {
            GolfHoleBean golfHoleBean = App.mGolfHoleList.get(i);
            mTitleDatas.add(new TitleData(golfHoleBean.holeName, golfHoleBean.ganNum));
        }
        //第一列

        //表格数据
        for (int i = 0; i < App.mPersonList.size(); i++) {
            ArrayList<TableData> tableDatas = new ArrayList<>();
            for (int j = 0; j < App.mGolfHoleList.size(); j++) {
                GolfHoleBean golfHoleBean = App.mGolfHoleList.get(j);
                tableDatas.add(new TableData(golfHoleBean.yardsNum, 0, 0, 0, App.mGolfHoleList.get(j).ganNum));
            }
            App.mTableLists.add(tableDatas);
        }
    }

    @Override
    public void onClickListener(int i, int j) {
        Log.d(TAG, "i = " + i + ",j = " + j);
        this.mRow = i;
        this.mColumn = j;
        showDialog(App.mTableLists.get(i).get(j));
    }

    private void showDialog(TableData tableData) {
        Log.d(TAG, "click tableData = " + tableData);
        WindowManager wm = (WindowManager) mContext.getSystemService(Context.WINDOW_SERVICE);

        App.WIDTH = wm.getDefaultDisplay().getWidth();
        App.HEIGHT = wm.getDefaultDisplay().getHeight();

        //联动选择器的更多用法，可参见AddressPicker和CarNumberPicker
        LinkagePicker.DataProvider provider = new MyPickerDataProvider(tableData.defaullNum);
        ArrayList<String> mBarsNum = StringUtils.getBarsNum(tableData.defaullNum);
        Log.d(TAG, "mBarsNum = " + mBarsNum);
        mPicker = new LinkagePicker(mContext, provider);
        //获取头布局和底布局
        mFooterViewHolder = new FooterViewHolder(mContext, this);
        mHeaderViewHolder = new HeaderViewHolder(mContext, mRow, mColumn , mPicker);

        mPicker.setCycleDisable(true);
        mPicker.setTextSize(UIUtils.sp2px(10));
        mPicker.setHeaderView(mHeaderViewHolder.getHeaderView());
        mPicker.setFooterView(mFooterViewHolder.getFooterView());
        mPicker.setWidth(mPicker.getScreenWidthPixels());
        mPicker.setHeight(App.mUserHeight);
        mPicker.setGravity(Gravity.BOTTOM);
        mPicker.setSelectedIndex(tableData.numOfGan == 0 ? tableData.defaullNum : tableData.numOfGan, tableData.numOfTui, tableData.numOfError);
        mPicker.setDividerVisible(true);

        mPicker.show();


    }

    private void initScreenParams() {
        DisplayMetrics dm = new DisplayMetrics();
        mContext.getWindowManager().getDefaultDisplay().getMetrics(dm);
        Log.d("WangJ", "屏幕高:" + dm.heightPixels);

        //应用区域
        Rect outRect1 = new Rect();
        mContext.getWindow().getDecorView().getWindowVisibleDisplayFrame(outRect1);
        mHeight = outRect1.height();
        App.mUserHeight = mHeight;
        Log.d("WangJ", "应用区顶部" + outRect1.top);
        Log.d("WangJ", "应用区高" + mHeight);
    }


    @Override
    public void cancel() {
        int FirstIndex = mPicker.getSelectedFirstIndex();
        int SecondIndex = mPicker.getSelectedSecondIndex();
        int ThirdIndex = mPicker.getSelectedThirdIndex();
        Log.d(TAG, "FirstIndex = " + FirstIndex + ",SecondIndex = " + SecondIndex + "ThirdIndex = " + ThirdIndex);
        mPicker.dismiss();
    }

    @Override
    public void positive() {
        int firstIndex = mPicker.getSelectedFirstIndex();
        int secondIndex = mPicker.getSelectedSecondIndex();
        int thirdIndex = mPicker.getSelectedThirdIndex();
        Log.d(TAG, "firstIndex = " + firstIndex + ",secondIndex = " + secondIndex + "thirdIndex = " + thirdIndex);
        TableData tableData = App.mTableLists.get(mHeaderViewHolder.getRow()).get(mHeaderViewHolder.getColumn());
        tableData.numOfGan = firstIndex;
        tableData.numOfTui = secondIndex;
        tableData.numOfError = thirdIndex;
        //刷新表格
        mMyTableAdapter.refresh(App.mTableLists);
        //刷新总计
        mTotalView = new TotalViewLayout(mContext, App.mTableLists).initView();
        mLayoutTotalView.removeAllViews();
        mLayoutTotalView.addView(mTotalView);

        mPicker.dismiss();
    }

    private void initPopView() {
        View contentView = LayoutInflater.from(mContext).inflate(R.layout.popuplayout, null);
        contentView.findViewById(R.id.zonggan).setOnClickListener(this);
        contentView.findViewById(R.id.gancha).setOnClickListener(this);
        mPopWnd = new PopupWindow(contentView);
        mPopWnd.setContentView(contentView);
        mPopWnd.setWidth(ViewGroup.LayoutParams.WRAP_CONTENT);
        mPopWnd.setHeight(ViewGroup.LayoutParams.WRAP_CONTENT);

        mPopWnd.setBackgroundDrawable(new BitmapDrawable());
        mPopWnd.setOutsideTouchable(true);
    }


    public static final String TAG = "ScroingFragment";

    @Override
    public void initListener() {
        mContentView.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                int height = mContentView.getHeight();

                ViewGroup.LayoutParams layoutParams = mContentEnd.getLayoutParams();
                layoutParams.height = height;
                Log.d(TAG, "height = " + height);
                mContentEnd.setLayoutParams(layoutParams);

                mContentView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            }
        });
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.reset(this);
    }


    @OnClick({R.id.layout_1, R.id.layout_scroing, R.id.tv_details})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.layout_1:
                //张开详情
                //                mLayout1.setVisibility(View.GONE);
                //                mTvDetails.setVisibility(View.VISIBLE);
                break;
            case R.id.layout_scroing:
                mPopWnd.showAsDropDown(mLayoutScroing);
                break;
            case R.id.tv_details:
                //收起详情
                //                mLayout1.setVisibility(View.VISIBLE);
                //                mTvDetails.setVisibility(View.GONE);
                break;
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.zonggan:
                T.showShort(mContext, "总杆");
                mPopWnd.dismiss();
                break;
            case R.id.gancha:
                T.showShort(mContext, "杆差");
                mPopWnd.dismiss();
                break;

        }
    }


}
